package com.zhouxiaoge.transaction.multi.web;

import com.zhouxiaoge.transaction.multi.dao.CustomerRepository;
import com.zhouxiaoge.transaction.multi.domain.Customer;
import com.zhouxiaoge.transaction.multi.service.CustomerServiceTxInAnnotation;
import com.zhouxiaoge.transaction.multi.service.CustomerServiceTxInCode;
import io.swagger.annotations.Api;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api
@RestController
@RequestMapping("/api/customer")
public class CustomerResource {

    private final JmsTemplate jmsTemplate;

    private final CustomerServiceTxInAnnotation customerService;
    private final CustomerServiceTxInCode customerServiceInCode;
    private final CustomerRepository customerRepository;

    public CustomerResource(JmsTemplate jmsTemplate, CustomerServiceTxInAnnotation customerService, CustomerServiceTxInCode customerServiceInCode, CustomerRepository customerRepository) {
        this.jmsTemplate = jmsTemplate;
        this.customerService = customerService;
        this.customerServiceInCode = customerServiceInCode;
        this.customerRepository = customerRepository;
    }

    @PostMapping("/annotation")
    public Customer createInAnnotation(@RequestBody Customer customer) {
        return customerService.create(customer);
    }

    @PostMapping("/code")
    public Customer createInCode(@RequestBody Customer customer) {
        return customerServiceInCode.create(customer);
    }

    @Transactional
    @PostMapping("/message/annotation")
    public void createMsgWithListener(@RequestParam String userName) {
        jmsTemplate.convertAndSend("customer:msg:new", userName);
    }

    @Transactional
    @PostMapping("/message/code")
    public void createMsgDirect(@RequestParam String userName) {
        jmsTemplate.convertAndSend("customer:msg2:new", userName);
    }

    @GetMapping
    public List<Customer> getAll() {
        return customerRepository.findAll();
    }

    @Transactional
    @GetMapping("/message")
    public String getMsg() {
        jmsTemplate.setReceiveTimeout(2000);
        Object reply = jmsTemplate.receiveAndConvert("customer:msg:reply");
        return String.valueOf(reply);
    }
}
